package com.sromku.simple.fb.example;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import com.example.hal.model.Utilisateur;
import com.example.hal.model.UtilisateurController;
import com.example.hal.model.UtilisateurFacebookController;
import com.facebook.FacebookException;
import com.facebook.LoggingBehavior;
import com.facebook.internal.ImageDownloader;
import com.facebook.internal.ImageRequest;
import com.facebook.internal.ImageResponse;
import com.facebook.internal.Logger;
import com.facebook.widget.ProfilePictureView.OnErrorListener;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.example.fragments.LoginFragment;
import com.sromku.simple.fb.example.utils.MyUser;
import com.sromku.simple.fb.example.utils.ProfileFacebook;
import com.sromku.simple.fb.example.utils.Utils;
import com.sromku.simple.fb.listeners.OnProfileListener;

public class ChargementActivity extends FragmentActivity {
	protected static final String TAG = ChargementActivity.class.getName();

	private SimpleFacebook mSimpleFacebook;
    private ImageRequest lastRequest;
    private OnErrorListener onErrorListener;
    private Bitmap imageContents;
    private ImageView image;

    private String profileId;
    private int queryHeight = ImageRequest.UNSPECIFIED_DIMENSION;
    private int queryWidth = ImageRequest.UNSPECIFIED_DIMENSION;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSimpleFacebook = SimpleFacebook.getInstance(this);

		// test local language
		//Utils.updateLanguage(getApplicationContext(), "en");
		setContentView(R.layout.activity_chargement);

		image = (ImageView)findViewById(R.id.avatartest);

		

		if(mSimpleFacebook.isLogin())
		{
			// startActivity(i);
           // finish();
			//mViewPager.setVisibility(true);
			//   DetailsFragment details = (DetailsFragment)          getFragmentManager().findFragmentById(R.id.pager);

			mSimpleFacebook.getProfile(new OnProfileListener() {

				@Override
				public void onThinking() {
				//	Log.d("onThinking","onThinking");
				}

				@Override
				public void onException(Throwable throwable) {
				//	Log.d("onException",throwable.toString());
				}

				@Override
				public void onFail(String reason) {
				//	Log.d("onFail","onFail");
				}

				@Override
				public void onComplete(Profile response) {
				//	Log.d("onComplete","onComplete");
					ProfileFacebook.profile=response;
					refreshUtilisateur();
				}

			});
		}
		else
		{
			if(MyUser.profile!=null)
			{
		
		       startActivity(new Intent(this, MainActivity.class));
		
				finish();
			}
			else
			{

		        startActivity(new Intent(this, LoginActivity.class));
		
		        finish();
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSimpleFacebook = SimpleFacebook.getInstance(this);
	/*	if(mSimpleFacebook.getSession().isOpened()){
			Intent i=new Intent(ChargementActivity.this, MainActivity.class);
			 startActivity(i);
           finish();
		}*/
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data);
	}

	
	private void refreshUtilisateur() {

		final Thread checkUpdate = new Thread() {
		    public void run() {

			
			Utilisateur u = new Utilisateur();
			//u.setDateDerConnection(new Date());
			u.setEmail(ProfileFacebook.profile.getEmail());
			u.setNom(ProfileFacebook.profile.getLastName());
			u.setPrenom(ProfileFacebook.profile.getFirstName());
			u.setAvatar(ProfileFacebook.profile.getId());
			u.setIdFacebook(ProfileFacebook.profile.getId());
			
			profileId=ProfileFacebook.profile.getId();
			queryWidth=200;
			queryHeight=200;
			sendImageRequestFacebook(true);
			
			/*
			Bundle params = new Bundle();
			params.putBoolean("redirect", false);
			params.putString("height", "200");
			params.putString("type", "normal");
			params.putString("width", "200");
			new Request(
			    session,
			    "/me/picture",
			    params,
			    HttpMethod.GET,
			    new Request.Callback() {
			        public void onCompleted(Response response) {
			        }
			    }
			).executeAsync();
			
			
			
			    Bitmap image = null;
			    DefaultHttpClient client = new DefaultHttpClient();
			    HttpGet request = new HttpGet("");
			    try {
			        HttpResponse response = client.execute(request);
			        HttpEntity entity = response.getEntity();

			        int imageLength = (int)(entity.getContentLength());

			        InputStream is = entity.getContent();

			        byte[] imageBlob = new byte[imageLength];

			        int bytesRead = 0;

			        // Pull the image's byte array

			        while (bytesRead < imageLength) {
			            int n = is.read(imageBlob, bytesRead, imageLength - bytesRead);
			            bytesRead= n;
			        }

			        image = BitmapFactory.decodeByteArray(imageBlob, 0, imageBlob.length);
			    } catch (Exception e) {
			        e.printStackTrace();
			    }
			
			*/
			//Log.e("refreshUtilisateur ",ProfileFacebook.profile..getPicture()+" ");
			
			// ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// imageContents.compress(CompressFormat.PNG, 0, bos);
		//	    return bos.toByteArray();
			//u.setImage(bos.toByteArray());
			u.setMode(1);
			
			final UtilisateurController uc = new UtilisateurController();
			try {
			    uc.update(u);
			    
			} catch (Exception e) {
			    return;
			}
		    }
		};
		checkUpdate.start();
		
		
		UtilisateurFacebookController myuser = new UtilisateurFacebookController();
	   Utilisateur u=null;
		try {
			u= myuser.getUtilisateur(ProfileFacebook.profile.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (u != null) {
			MyUser.profile=u;

            startActivity(new Intent(this, MainActivity.class));

            finish();
            
		}
		else
		{
			MyUser.profile=null;
			
	        startActivity(new Intent(this, LoginActivity.class));
	
	        finish();
		}
	}

	
	
	private void sendImageRequestFacebook(boolean allowCachedResponse) {
        try {
            ImageRequest.Builder requestBuilder = new ImageRequest.Builder(
                    getApplicationContext(),
                    ImageRequest.getProfilePictureUrl(profileId, queryWidth,  queryHeight));

            ImageRequest request = requestBuilder.setAllowCachedRedirects(true)
                    .setCallerTag(this)
                    .setCallback(
                    new ImageRequest.Callback() {
                        @Override
                        public void onCompleted(ImageResponse response) {
                            processResponseFacebook(response);
                        }
                    })
                    .build();

            // Make sure to cancel the old request before sending the new one to prevent
            // accidental cancellation of the new request. This could happen if the URL and
            // caller tag stayed the same.
            if (lastRequest != null) {
                ImageDownloader.cancelRequest(lastRequest);
            }
            lastRequest = request;

            ImageDownloader.downloadAsync(request);
        } catch (URISyntaxException e) {
            Logger.log(LoggingBehavior.REQUESTS, Log.ERROR, TAG, e.toString());
        }
    }
	
	 private void processResponseFacebook(ImageResponse response) {
	        // First check if the response is for the right request. We may have:
	        // 1. Sent a new request, thus super-ceding this one.
	        // 2. Detached this view, in which case the response should be discarded.
	        if (response.getRequest() == lastRequest) {
	            lastRequest = null;
	            Bitmap responseImage = response.getBitmap();
	            Exception error = response.getError();
	            if (error != null) {
	                OnErrorListener listener = onErrorListener;
	                if (listener != null) {
	                    listener.onError(new FacebookException(
	                            "Error in downloading profile picture for profileId: " + profileId, error));
	                } else {
	                    Logger.log(LoggingBehavior.REQUESTS, Log.ERROR, TAG, error.toString());
	                }
	            } else if (responseImage != null) {
	                setImageBitmap(responseImage);

	                if (response.isCachedRedirect()) {
	                    sendImageRequestFacebook(false);
	                }
	            }
	        }
	    }
	 
	  private void setImageBitmap(Bitmap imageBitmap) {
	        if (image != null && imageBitmap != null) {
	            imageContents = imageBitmap; // Hold for save-restore cycles
	            image.setImageBitmap(imageBitmap);
	        }
	    }

}
